<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Notice as NoticeModel;
use think\Db;

class Notice extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 获取通知列表（支持 tab: unread|read|all）
     * 入参：page, pageSize, tab, searchKey
     * 出参：list, total, unread_count
     */
    public function getNoticeList()
    {
        $page = (int)$this->request->post('page', 1);
        $pageSize = (int)$this->request->post('pageSize', 20);
        $searchKey = $this->request->post('searchKey', '');


        $where = [];
        // 搜索：标题或内容模糊
        if ($searchKey) {
            $where['title|content'] = ['like', "%{$searchKey}%"];
        }

        $noticeModel = new NoticeModel();
        // 总数
        $total = $noticeModel->where($where)->count();

        // 列表
        $list = $noticeModel
            ->where($where)
            ->whereNull('deletetime')
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

    
        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }



    public function userNoticeList()
    {
        $page = (int)$this->request->post('page', 1);
        $pageSize = (int)$this->request->post('pageSize', 20);
        $tab = $this->request->post('tab', 'all'); // unread | read | all
        $searchKey = $this->request->post('searchKey', '');
        $userId = (int)$this->auth->id;

        // 主表：user_notice 别名 un，关联 notice n
        $baseQuery = Db::name('user_notice')->alias('un')
            ->join('notice n', 'n.id = un.notice_id')
            ->join('user u', 'u.id = un.user_id')
            ->where('un.user_id', $userId)
            ->whereNull('un.deletetime');

        // 搜索：标题或内容模糊
        if ($searchKey) {
            $baseQuery = $baseQuery->where('n.title|n.content', 'like', "%{$searchKey}%");
        }


     

        // 统计所有总数
        $allcountQuery = clone $baseQuery;
        $allcount = $allcountQuery->count();


        // tab 过滤
        if ($tab === 'unread') {
            $baseQuery = $baseQuery->where('un.is_read', 0);
        } elseif ($tab === 'read') {
            $baseQuery = $baseQuery->where('un.is_read', 1);
        }

        // 统计总数
        $countQuery = clone $baseQuery;
        $total = $countQuery->count();

        // 列表
        $list = $baseQuery
            ->field('n.*,u.name as user_name,un.id,un.is_read')
            ->order('n.id', 'desc')
            ->page($page, $pageSize)
            ->select();

        // 未读总数（不受 tab 影响，但受搜索条件影响更贴合页面展示）
        $unreadQuery = Db::name('user_notice')->alias('un')
            ->join('notice n', 'n.id = un.notice_id')
            ->where('un.user_id', $userId)
            ->whereNull('un.deletetime')
            ->where('un.is_read', 0);
        if ($searchKey) {
            $unreadQuery = $unreadQuery->where('n.title|n.content', 'like', "%{$searchKey}%");
        }
        $unreadCount = (int)$unreadQuery->count('un.id');

        $readCount=$allcount-$unreadCount;
        $this->success('请求成功', [
            'list' => $list,
            'total' => $total,
            'unread_count' => $unreadCount,
            'read_count' => $readCount,
        ]);
    }

    /**
     * 创建公告
     * 支持发布范围：全公司、部门、角色、人员
     */
    public function createNotice()
    {
        // 清空全局过滤，保留富文本HTML
        $this->request->filter([]);
        $data = $this->request->post();
        
        // 验证必填字段
        if (empty($data['title'])) {
            $this->error('标题不能为空');
        }
        if (empty($data['content'])) {
            $this->error('内容不能为空');
        }
        
        // 验证发布范围
        $publishType = $data['publishType'] ?? 'all';
        if (!in_array($publishType, ['all', 'dept', 'role', 'user'])) {
            $this->error('发布范围类型错误');
        }
        

            $notice = new NoticeModel();
            $notice->title = $data['title'];
            $notice->content = $data['content'];
            $notice->publish_type = $publishType;
            $notice->publish_config = json_encode([
                'deptIds' => $data['deptIds'] ?? [],
                'roleIds' => $data['roleIds'] ?? [],
                'userIds' => $data['userIds'] ?? []
            ]);
            $notice->createtime = date('Y-m-d H:i:s');
            $notice->save();
            
            $noticeId = $notice->id;
            
            // 根据发布范围创建用户通知记录
            $this->createUserNotices($noticeId, $publishType, $data);
            
           
            $this->success('创建成功');
       
    }

    /**
     * 更新公告
     * 支持发布范围：全公司、部门、角色、人员
     */
    public function updateNotice()
    {
        // 清空全局过滤，保留富文本HTML
        $this->request->filter([]);
        $data = $this->request->post();

        if (empty($data['id'])) {
            $this->error('缺少ID');
        }
        
        // 验证必填字段
        if (empty($data['title'])) {
            $this->error('标题不能为空');
        }
        if (empty($data['content'])) {
            $this->error('内容不能为空');
        }
        
        // 验证发布范围
        $publishType = $data['publishType'] ?? 'all';
        if (!in_array($publishType, ['all', 'dept', 'role', 'user'])) {
            $this->error('发布范围类型错误');
        }

        // 开启事务
        Db::startTrans();
        try {
            $noticeId = (int)$data['id'];
            
            // 更新公告
            $notice = new NoticeModel();
            $updateData = [
                'title' => $data['title'],
                'content' => $data['content'],
                'publish_type' => $publishType,
                'publish_config' => json_encode([
                    'deptIds' => $data['deptIds'] ?? [],
                    'roleIds' => $data['roleIds'] ?? [],
                    'userIds' => $data['userIds'] ?? []
                ]),
                'updatetime' => date('Y-m-d H:i:s')
            ];

            $res = $notice->where('id', $noticeId)->update($updateData);
            if ($res === false) {
                throw new \Exception('更新公告失败');
            }
            
            // 删除原有的用户通知记录
            Db::name('user_notice')->where('notice_id', $noticeId)->delete();
            
            // 重新创建用户通知记录
            $this->createUserNotices($noticeId, $publishType, $data);
            
            Db::commit();
            $this->success('更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('更新失败：' . $e->getMessage());
        }
    }
    
    /**
     * 根据发布范围创建用户通知记录
     */
    private function createUserNotices($noticeId, $publishType, $data)
    {
        $userIds = [];
        
        switch ($publishType) {
            case 'all':
                // 全公司：获取所有用户
                $userIds = Db::name('user')->where('status', 'normal')->column('id');
                break;
                
            case 'dept':
                // 部门：根据部门ID获取用户
                $deptIds = $data['deptIds'] ?? [];
                if (!empty($deptIds)) {
                    $userIds = Db::name('user')
                        ->where('status', 'normal')
                        ->whereIn('department_id', $deptIds)
                        ->column('id');
                }
                break;
                
            case 'role':
                // 角色：根据角色ID获取用户
                $roleIds = $data['roleIds'] ?? [];
                if (!empty($roleIds)) {
                    $userIds = Db::name('user')
                    ->where('status', 'normal')
                    ->whereIn('role_id', $roleIds)
                    ->column('id');
                }
                break;
                
            case 'user':
                // 人员：直接使用指定用户ID
                $userIds = $data['userIds'] ?? [];
                break;
        }
        
        // 去重并创建用户通知记录
        $userIds = array_unique($userIds);
        if (!empty($userIds)) {
            $insertData = [];
            foreach ($userIds as $userId) {
                $insertData[] = [
                    'notice_id' => $noticeId,
                    'user_id' => $userId,
                    'is_read' => 0,
                    'createtime' => date('Y-m-d H:i:s')
                ];
            }
            Db::name('user_notice')->insertAll($insertData);
        }
    }
    // 删除公告

    public function deleteNotice()
    {
        $data = $this->request->post();
        $id = $data['id'] ?? null;
        
        if (empty($id)) {
            $this->error('缺少ID');
        }
        
        $noticeId = (int)$id;
        
        // 软删除公告（设置删除时间）
        $notice = new NoticeModel();
        $notice->where('id', $noticeId)->update([
            'deletetime' => time()
        ]);
    
        // 删除相关的用户通知记录
        Db::name('user_notice')->where('notice_id', $noticeId)->delete();
        
        
        $this->success('删除成功');
    
    }


    // 批量删除公告
   
    public function deleteMulty()
    {
        $data = $this->request->post();
        $ids = $data['ids'] ?? [];
        
        if (empty($ids) || !is_array($ids)) {
            $this->error('缺少要删除的ID列表');
        }
        
        $noticeIds = array_map('intval', $ids);
        
        // 软删除公告（设置删除时间）
        $notice = new NoticeModel();
        $notice->whereIn('id', $noticeIds)->update([
            'deletetime' => time()
        ]);
        // 删除相关的用户通知记录
        Db::name('user_notice')->whereIn('notice_id', $noticeIds)->delete();
        
        $this->success('批量删除成功');
       
    }

    //单个已读
    
    public function readNotice()
    {
        $data = $this->request->post();
        $id = $data['id'] ?? null;
        
        if (empty($id)) {
            $this->error('缺少要删除的ID列表');
        }
        // 更新用户通知记录为已读
        Db::name('user_notice')->where('id', $id)->update(['is_read' => 1]);
        $this->success('已读成功');
       
    }


    //批量已读
    public function readMulty()
    {
        $data = $this->request->post();
 
        $userId = (int)$this->auth->id;
        // 更新用户通知记录为已读
        Db::name('user_notice')->where('user_id', $userId)->update(['is_read' => 1]);
        $this->success('批量已读成功');
    }

    
    
    /**
     * 清空所有通知
     */
    public function clearAll()
    {
        $userId = (int)$this->auth->id;
        
    // 删除当前用户所有通知记录
        Db::name('user_notice')
        ->where('user_id', $userId)
        ->update(['deletetime' => time()]);
            
       $this->success('清空通知成功');
     
    }


     /**
    * 删除单个通知
    */
    public function removeOne()
    {
        $data = $this->request->post();
        $noticeId = (int)($data['id'] ?? 0);
        $userId = (int)$this->auth->id;
        
        if (empty($noticeId)) {
            $this->error('缺少通知ID');
        }
      
        // 删除当前用户的指定通知记录
        $res = Db::name('user_notice')
            ->where('id', $noticeId)
            ->update(['deletetime' => time()]);
        
        
        $this->success('删除通知成功');
      
    }
    
   
 
 
 
 
}